<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Service\Dao;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\Answer;
use HyperfX\Utils\Service;

class AnswerDao extends Service
{
    public function first(int $id, $throw = false): ?Answer
    {
        $model = Answer::query()->find($id);
        if (empty($model) && $throw) {
            throw new BusinessException(ErrorCode::ANSWER_NOT_EXIST);
        }
        return $model;
    }

    public function firstCache(int $id, $throw = false): ?Answer
    {
        $model = Answer::findFromCache($id);
        if (empty($model) && $throw) {
            throw new BusinessException(ErrorCode::ANSWER_NOT_EXIST);
        }
        return $model;
    }

    public function find(int $questionId, int $offset, int $limit)
    {
        $query = Answer::query()->with(['user'])->where('question_id', $questionId);

        return $this->factory->model->pagination($query, $offset, $limit);
    }
}
